<?php
declare (strict_types=1);

namespace app\admin\model;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use app\services\wechat\Offiaccount;
use think\Model;
use app\home\model\Config;


/**
 * @mixin \think\Model
 */
class MessageTemplate extends Model
{
    protected $name = "message_template";



    public function sendMessage($openid, $data, $title)
    {
        try {
            $messageInfo = $this->where(['title' => $title])->where(['type' => 1])->find();
            if (empty($messageInfo)) {
                return ['code' => 1];
            }
            $result = ['code' => 1];
            if ($messageInfo['status'] == 1 && $messageInfo['tid']) {
                $Offiaccount = new Offiaccount();
                $result = $Offiaccount->Message($openid, $data, $messageInfo['tid']);

            }

        } catch (\Exception $exception) {
            return false;
        }
        return $result;
    }

    public function sendAliMessage($phone, $title, $field)
    {

        try {
            $messageInfo = $this->where(['title' => $title])->where(['type' => 2])->find();
            if (empty($messageInfo)) {
                return false;
            }

            if ($messageInfo['status'] == 1) {

                $accessKeyId = Config::getConfigValue('ali_duanxin_access_key_secret');//为企阿里云账号秘钥ID
                $accessKeySecret = Config::getConfigValue('ali_duanxin_access_key_id');;//秘钥

                $config = new Config(['accessKeyId' => $accessKeyId, 'accessKeySecret' => $accessKeySecret]);
                $config->endpoint = "dysmsapi.aliyuncs.com";
                $client = new \AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi($config);
                $sendSmsRequest = new SendSmsRequest([
                    "phoneNumbers" => $phone,
                    "signName" => $messageInfo['template_name'],    //    签名
                    "templateCode" => $messageInfo['tid'],    //    模板
                    "templateParam" => json_encode($field)
                ]);
                $runtime = new RuntimeOptions([]);
                $res = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
                if ($res->body->code == 'OK') {
                    return true;
                }
                return false;

            } else {
                return false;
            }
        } catch (\Exception $exception) {
            return false;
        }


    }
}



